/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hutool.core.collection.CollectionUtil;
import com.anwen.mongo.aggregate.Aggregate;
import com.anwen.mongo.aggregate.AggregateWrapper;
import com.anwen.mongo.aggregate.pipeline.Accumulators;
import com.anwen.mongo.bson.MongoPlusDocument;
import com.anwen.mongo.conditions.interfaces.ConditionOperators;
import com.anwen.mongo.conditions.interfaces.condition.CompareCondition;
import com.anwen.mongo.conditions.query.LambdaQueryChainWrapper;
import com.anwen.mongo.conditions.query.QueryWrapper;
import com.anwen.mongo.conditions.update.LambdaUpdateChainWrapper;
import com.anwen.mongo.mapper.BaseMapper;
import com.anwen.mongo.mapping.TypeReference;
import com.anwen.mongo.model.PageResult;
import com.anwen.mongo.service.impl.ServiceImpl;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.excel.utils.ExcelUtil;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.constant.MongoDataConstant;
import com.comac.ins.isfd.constant.enums.AlgorithmArrangementEnum;
import com.comac.ins.isfd.constant.enums.IsfdAnalysisApplicationTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdAnalysisClassificationTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdAnalysisConfigNodeTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdAnalysisMaterialTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdAnalysisTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdMetadataTableNameEnum;
import com.comac.ins.isfd.domain.IsfdAnalysis;
import com.comac.ins.isfd.domain.IsfdAnalysisConfig;
import com.comac.ins.isfd.domain.IsfdAnalysisParameterConfig;
import com.comac.ins.isfd.domain.IsfdOperator;
import com.comac.ins.isfd.domain.bo.AlgorithmArrangementBo;
import com.comac.ins.isfd.domain.bo.IsfdAnalysisBo;
import com.comac.ins.isfd.domain.bo.query.IsfdAnalysisQueryBo;
import com.comac.ins.isfd.domain.vo.IsfdAnalysisConfigVo;
import com.comac.ins.isfd.domain.vo.IsfdAnalysisCountObjectVo;
import com.comac.ins.isfd.domain.vo.IsfdAnalysisCountResultObjectVo;
import com.comac.ins.isfd.domain.vo.IsfdAnalysisDisplayNameVo;
import com.comac.ins.isfd.domain.vo.IsfdAnalysisVo;
import com.comac.ins.isfd.service.IIsfdAnalysisConfigService;
import com.comac.ins.isfd.service.IIsfdAnalysisParameterConfigService;
import com.comac.ins.isfd.service.IIsfdAnalysisService;
import com.comac.ins.isfd.service.IIsfdCalculationExampleService;
import com.comac.ins.isfd.service.IIsfdMetadataImportService;
import com.comac.ins.isfd.service.IIsfdOperatorService;
import com.mongodb.client.MongoCollection;
import lombok.extern.slf4j.Slf4j;

/**
 * 算法service实现类
 *
 * @author hxloongs
 * @date 2024-7-9
 */
@Slf4j
@Service
public class IsfdAnalysisServiceImpl extends ServiceImpl<IsfdAnalysis> implements IIsfdAnalysisService, MongoDataConstant, IIsfdMetadataImportService {

    @Autowired
    private IIsfdAnalysisConfigService iIsfdAnalysisConfigService;

    @Autowired
    private IIsfdAnalysisParameterConfigService iIsfdAnalysisParameterConfigService;

    @Autowired
    private IIsfdOperatorService iIsfdOperatorService;

    @Autowired
    private IIsfdCalculationExampleService iIsfdCalculationExampleService;

    @Autowired
    private BaseMapper baseMapper;

    private final static SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<IsfdAnalysisCountObjectVo> listCount() {
        List<IsfdAnalysisCountObjectVo> result = new ArrayList<>();
        List<IsfdAnalysis> isfdAnalysisList = this.list();

        // 1. 处理脏数据，如果 application_type classification_type material_type 根据枚举类型来判断
        isfdAnalysisList = isfdAnalysisList.stream().filter(ial -> IsfdAnalysisApplicationTypeEnum.forValue(ial.getApplicationType()) != null
            && IsfdAnalysisClassificationTypeEnum.forValue(ial.getClassificationType()) != null
            && IsfdAnalysisMaterialTypeEnum.forValue(ial.getMaterialType()) != null).toList();

        if (CollectionUtil.isNotEmpty(isfdAnalysisList)) {
            // 2. 解析applicationType层
            Map<String, List<IsfdAnalysis>> applicationTypeMap = isfdAnalysisList.stream().collect(Collectors.groupingBy(IsfdAnalysis::getApplicationType));
            for (String applicationType : applicationTypeMap.keySet()) {
                List<IsfdAnalysis> classificationTypeList = applicationTypeMap.get(applicationType);

                IsfdAnalysisCountObjectVo applicationTypeVo = new IsfdAnalysisCountObjectVo();
                applicationTypeVo.setType(applicationType);
                applicationTypeVo.setName(IsfdAnalysisApplicationTypeEnum.getDescByValue(applicationType));
                applicationTypeVo.setCount((long) classificationTypeList.size());
                List<IsfdAnalysisCountObjectVo> applicationTypeChildren = new ArrayList<>();
                // 3. 解析classificationType层
                Map<String, List<IsfdAnalysis>> classificationTypeMap = classificationTypeList.stream().collect(Collectors.groupingBy(IsfdAnalysis::getClassificationType));
                for (String classificationType : classificationTypeMap.keySet()) {
                    IsfdAnalysisCountObjectVo classificationTypeVo = new IsfdAnalysisCountObjectVo();
                    classificationTypeVo.setType(classificationType);
                    classificationTypeVo.setName(IsfdAnalysisClassificationTypeEnum.getDescByValue(classificationType));
                    classificationTypeVo.setCount((long) classificationTypeMap.get(classificationType).size());
                    applicationTypeChildren.add(classificationTypeVo);
                }

                applicationTypeVo.setChildren(applicationTypeChildren);
                result.add(applicationTypeVo);
            }
        }
        return result;
    }

    @Override
    public List<IsfdAnalysisCountResultObjectVo> listCountByListByField(String field) {
        AggregateWrapper groupAggregateWrapper = new AggregateWrapper();
        groupAggregateWrapper.group("$" + field,
            Accumulators.sum(field, 1));

        List<Map<String, Object>> maps = baseMapper.aggregateList(DB_NAME, ANALYSIS_LIST_COLLECTION_NAME, groupAggregateWrapper, new TypeReference<Map<String, Object>>() {
        });
        return maps.stream()
            .map(item -> new IsfdAnalysisCountResultObjectVo(null, (String) item.get("_id"), Long.valueOf(item.get(field).toString())))
            .toList();
    }

    private String convertToCamelCase(String field) {
        if (field == null || !field.contains("_")) {
            return field;
        }
        StringBuilder result = new StringBuilder();
        boolean toUpperCase = false;
        for (char c : field.toCharArray()) {
            if (c == '_') {
                toUpperCase = true;
            } else {
                if (toUpperCase) {
                    result.append(Character.toUpperCase(c));
                    toUpperCase = false;
                } else {
                    result.append(Character.toLowerCase(c));
                }
            }
        }
        return result.toString();
    }

    @Override
    public List<IsfdAnalysisCountResultObjectVo> listTimeCount(String originalField, Date startTime, Date endTime) {
        // 将下划线命名转为驼峰命名
        String field = convertToCamelCase(originalField);
        List<IsfdAnalysisCountResultObjectVo> result = new ArrayList<>();
//        this.

        LambdaQueryChainWrapper<IsfdAnalysis> queryChainWrapper = this.lambdaQuery();

        if (startTime != null || endTime != null) {
            if (startTime != null) {
                queryChainWrapper.gte(IsfdAnalysis::getCreateTime, startTime);
            }
            if (endTime != null) {
                queryChainWrapper.lte(IsfdAnalysis::getCreateTime, endTime);
            }
        }

        List<IsfdAnalysis> isfdAnalyseList = this.list(queryChainWrapper);

        Map<String, Map<String, Long>> groupedData = new HashMap<>();

        Set<String> allMonths = new HashSet<>();
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");

        for (IsfdAnalysis analysis : isfdAnalyseList) {
            String month = monthFormat.format(analysis.getCreateTime());
            String fieldValue = (field != null) ? getFieldValue(analysis, field) : null;

            allMonths.add(month);
            groupedData.putIfAbsent(month, new HashMap<>());

            Map<String, Long> monthGroup = groupedData.get(month);
            if (fieldValue != null) {
                monthGroup.put(fieldValue, monthGroup.getOrDefault(fieldValue, 0L) + 1);
            } else {
                monthGroup.put("null", monthGroup.getOrDefault("null", 0L) + 1);
            }
        }

        for (String month : allMonths) {
            Map<String, Long> monthGroup = groupedData.get(month);
            if (monthGroup == null) {
                monthGroup = new HashMap<>();
                groupedData.put(month, monthGroup);
            }

        }

        for (String month : allMonths) {
            Map<String, Long> monthGroup = groupedData.get(month);
            for (Map.Entry<String, Long> subEntry : monthGroup.entrySet()) {
                String fieldValue = subEntry.getKey();
                Long count = subEntry.getValue();
                result.add(new IsfdAnalysisCountResultObjectVo(month, fieldValue, count));
            }
        }
        result.sort(Comparator.comparing(IsfdAnalysisCountResultObjectVo::getTime));

        return result;
    }

    private String getFieldValue(IsfdAnalysis analysis, String field) {
        try {
            Field fieldObj = IsfdAnalysis.class.getDeclaredField(field);
            fieldObj.setAccessible(true);
            Object value = fieldObj.get(analysis);
            return value != null ? value.toString() : null;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    private <T> List<T> execute(String collectionName, Aggregate<?> aggregate, Class<T> clazz) {
        return baseMapper.aggregateList(collectionName, aggregate, clazz);
    }


    @Override
    public TableDataInfo<IsfdAnalysisVo> queryPageList(IsfdAnalysisQueryBo queryBo) {
        // 构造返回对象列表
        List<IsfdAnalysisVo> resultList = new ArrayList<>();
        List<IsfdAnalysis> isfdAnalyseList = new ArrayList<>();
        Integer pageNum = queryBo.getPageNum();
        Integer pageSize = queryBo.getPageSize();

        // 构造查询参数
        LambdaQueryChainWrapper<IsfdAnalysis> queryChainWrapper = this.lambdaQuery();
        if (PageQuery.DEFAULT_ASC.equals(queryBo.getIsAsc())) {
            queryChainWrapper.orderByDesc(IsfdAnalysis::getCreateTime);
        } else {
            queryChainWrapper.orderByAsc(IsfdAnalysis::getCreateTime);
        }

        queryChainWrapper.like(StringUtils.isNotBlank(queryBo.getAnalysisType()), IsfdAnalysis::getAnalysisType, queryBo.getAnalysisType());
        queryChainWrapper.like(StringUtils.isNotBlank(queryBo.getDisplayName()), IsfdAnalysis::getDisplayName, queryBo.getDisplayName());
        queryChainWrapper.eq(null != queryBo.getIsPublished(), IsfdAnalysis::getIsPublished, queryBo.getIsPublished());
        queryChainWrapper.eq(null != queryBo.getUploadedHelpDoc(), IsfdAnalysis::getUploadedHelpDoc, queryBo.getUploadedHelpDoc());
        queryChainWrapper.eq(null != queryBo.getUploadedResultTemplate(), IsfdAnalysis::getUploadedResultTemplate, queryBo.getUploadedResultTemplate());
        queryChainWrapper.in(CollectionUtil.isNotEmpty(queryBo.getMetadataManagementIds()), IsfdAnalysis::getMetadataManagementId, queryBo.getMetadataManagementIds());
        try {
            if (StringUtils.isNotBlank(queryBo.getPublishedStartTime())) {
                queryChainWrapper.gte(IsfdAnalysis::getPublishedTime, SIMPLE_DATE_FORMAT.parse(queryBo.getPublishedStartTime()));
            }
            if (StringUtils.isNotBlank(queryBo.getPublishedEndTime())) {
                queryChainWrapper.lte(IsfdAnalysis::getPublishedTime, SIMPLE_DATE_FORMAT.parse(queryBo.getPublishedEndTime()));
            }
        } catch (Exception e) {
            throw new BaseException("发布时间查询格式转化错误！");
        }
        if (CollectionUtil.isNotEmpty(queryBo.getCalculateObjects())) {
            List<Bson> bsonList = new ArrayList<>();
            for (IsfdAnalysisQueryBo.CalculateObject calculateObject : queryBo.getCalculateObjects()) {
                MongoPlusDocument mongoPlusDocument = new MongoPlusDocument();
                mongoPlusDocument.put("object_type", calculateObject.getObjectType());
                if (StringUtils.isNotBlank(calculateObject.getObjectName())) {
                    mongoPlusDocument.put("object_name", calculateObject.getObjectName());
                }
                bsonList.add(mongoPlusDocument);
            }
            queryChainWrapper.all("calculate_object", bsonList);
        }

        // 当存在type list 的数据的时候，将级联查询从列表中循环处理
        // 否则进行正常的mongodb分页查询
        Boolean needPageMemoryLimit = Boolean.FALSE;
        Long total = null;
        if (CollectionUtil.isNotEmpty(queryBo.getTypeList())) {
            AtomicInteger counter = new AtomicInteger(0);
            for (IsfdAnalysisQueryBo.TypeList type : queryBo.getTypeList()) {
                // 第一次要让queryChainWrapper的条件加入进去
                // 除了第一次以外都是替换其中的value值
                if (counter.get() == 0) {
                    queryChainWrapper.eq(StringUtils.isNotBlank(type.getApplicationType()), IsfdAnalysis::getApplicationType, type.getApplicationType());
                    queryChainWrapper.eq(StringUtils.isNotBlank(type.getClassificationType()), IsfdAnalysis::getClassificationType, type.getClassificationType());
                    queryChainWrapper.eq(StringUtils.isNotBlank(type.getMaterialType()), IsfdAnalysis::getMaterialType, type.getMaterialType());
                } else {
                    List<CompareCondition> compareList = queryChainWrapper.getCompareList();
                    for (CompareCondition condition : compareList) {
                        String column = condition.getColumn();
                        if (IsfdAnalysisTypeEnum.APPLICATION_TYPE.getValue().equals(column)) {
                            condition.setValue(type.getApplicationType());
                        }
                        if (IsfdAnalysisTypeEnum.CLASSIFICATION_TYPE.getValue().equals(column)) {
                            condition.setValue(type.getClassificationType());
                        }
                        if (IsfdAnalysisTypeEnum.MATERIAL_TYPE.getValue().equals(column)) {
                            condition.setValue(type.getMaterialType());
                        }
                    }
                }
                isfdAnalyseList.addAll(this.list(queryChainWrapper));
                counter.incrementAndGet();
            }
            // 做时间倒序排序
            isfdAnalyseList.sort(Comparator.comparing(IsfdAnalysis::getCreateTime).reversed());
            // 判断是否需要内存分页
            needPageMemoryLimit = Boolean.TRUE;
        } else {
            PageResult<IsfdAnalysis> page = this.page(queryChainWrapper, pageNum, pageSize);
            isfdAnalyseList.addAll(page.getContentData());
            total = page.getTotalSize();
        }

        // 实体类装成vo返回
        resultList = MapstructUtils.convert(isfdAnalyseList, IsfdAnalysisVo.class);
        TableDataInfo<IsfdAnalysisVo> resultTable = TableDataInfo.buildToPageMemoryLimit(needPageMemoryLimit, resultList, pageNum, pageSize, total);
        resultTable.getRows().forEach(i -> {
            i.setUploadedHelpDoc(iIsfdCalculationExampleService.checkIfExistCalculationExample(i.getAnalysisType()));
        });
        return resultTable;
    }

    @Override
    public Boolean add(IsfdAnalysisBo isfdAnalysisBo) {
        LambdaQueryChainWrapper<IsfdAnalysis> queryChainWrapperForType = this.lambdaQuery();
        queryChainWrapperForType.eq(IsfdAnalysis::getAnalysisType, isfdAnalysisBo.getAnalysisType());
        List<IsfdAnalysis> listForType = this.list(queryChainWrapperForType);
        if (CollectionUtil.isNotEmpty(listForType)) {
            throw new BaseException("算法类型不可重复，请修改！");
        }

        LambdaQueryChainWrapper<IsfdAnalysis> queryChainWrapperForName = this.lambdaQuery();
        queryChainWrapperForName.eq(IsfdAnalysis::getDisplayName, isfdAnalysisBo.getDisplayName());
        List<IsfdAnalysis> listForName = this.list(queryChainWrapperForName);
        if (CollectionUtil.isNotEmpty(listForName)) {
            throw new BaseException("displayName不可重复，请修改！");
        }

        isfdAnalysisBo.setCreateTime(new Date());
        isfdAnalysisBo.setIsPublished(Boolean.FALSE);
        isfdAnalysisBo.setUploadedHelpDoc(Boolean.FALSE);
        isfdAnalysisBo.setUploadedResultTemplate(Boolean.FALSE);
        IsfdAnalysis isfdAnalysis = MapstructUtils.convert(isfdAnalysisBo, IsfdAnalysis.class);

        return this.save(isfdAnalysis);
    }

    @Override
    public Boolean update(IsfdAnalysisBo isfdAnalysisBo) {
        IsfdAnalysis isfdAnalysis = this.getById(isfdAnalysisBo.get_id());
        if (isfdAnalysis == null) {
            throw new BaseException("修改的算法不存在，请确认后重试！");
        }
        isfdAnalysis.setDisplayName(isfdAnalysisBo.getDisplayName());
        isfdAnalysis.setApplicationType(isfdAnalysisBo.getApplicationType());
        isfdAnalysis.setClassificationType(isfdAnalysisBo.getClassificationType());
        isfdAnalysis.setMaterialType(isfdAnalysisBo.getMaterialType());
        List<IsfdAnalysis.CalculateObject> calculateObjects = new ArrayList<>();
        for (IsfdAnalysisBo.CalculateObject object : isfdAnalysisBo.getCalculateObjects()) {
            IsfdAnalysis.CalculateObject targetObject = new IsfdAnalysis.CalculateObject();
            targetObject.setObjectName(object.getObjectName());
            targetObject.setObjectType(object.getObjectType());
            calculateObjects.add(targetObject);
        }
        isfdAnalysis.setCalculateObjects(calculateObjects);

        return this.saveOrUpdate(isfdAnalysis);
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids) {
        for (String id : ids) {
            // 将算法层的参数配置进行删除
            LambdaUpdateChainWrapper<IsfdAnalysisParameterConfig> updateChainWrapperForParameterConfig = iIsfdAnalysisParameterConfigService.lambdaUpdate();
            updateChainWrapperForParameterConfig.eq(IsfdAnalysisParameterConfig::getAnalysisRefId, id);
            iIsfdAnalysisParameterConfigService.remove(updateChainWrapperForParameterConfig);

            // 将算法相关的编配配置删除
            LambdaUpdateChainWrapper<IsfdAnalysisConfig> updateChainWrapperForConfig = iIsfdAnalysisConfigService.lambdaUpdate();
            updateChainWrapperForConfig.eq(IsfdAnalysisConfig::getAnalysisRefId, id);
            iIsfdAnalysisConfigService.remove(updateChainWrapperForConfig);

            // 删除算法
            this.removeById(id);
        }
        return Boolean.TRUE;
    }

    @Override
    public TableDataInfo<IsfdAnalysisDisplayNameVo> getPageListByOperatorRefId(String operatorRefId, PageQuery pageQuery) {
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        LambdaQueryChainWrapper<IsfdAnalysisConfig> queryChainWrapper = iIsfdAnalysisConfigService.lambdaQuery();
        queryChainWrapper.eq(IsfdAnalysisConfig::getNodeType, IsfdAnalysisConfigNodeTypeEnum.OPERATOR.getValue());
        queryChainWrapper.eq(IsfdAnalysisConfig::getOperatorRefId, operatorRefId);
        List<IsfdAnalysisConfig> isfdAnalysisConfigList = iIsfdAnalysisConfigService.list(queryChainWrapper);
        List<String> analysisIdList = isfdAnalysisConfigList.stream().map(IsfdAnalysisConfig::getAnalysisRefId).distinct().toList();
        if (CollectionUtil.isEmpty(analysisIdList)) {
            return TableDataInfo.build();
        }
        LambdaQueryChainWrapper<IsfdAnalysis> isfdAnalysisLambdaQueryChainWrapper = this.lambdaQuery();
        isfdAnalysisLambdaQueryChainWrapper.in(IsfdAnalysis::get_id, analysisIdList);
        List<IsfdAnalysis> isfdAnalysisList = this.list(isfdAnalysisLambdaQueryChainWrapper);
        List<IsfdAnalysisDisplayNameVo> resultList = new ArrayList<>();
        for (IsfdAnalysis isfdAnalysis : isfdAnalysisList) {
            IsfdAnalysisDisplayNameVo isfdAnalysisDisplayNameVo = new IsfdAnalysisDisplayNameVo();
            String analysisType = isfdAnalysis.getAnalysisType();
            isfdAnalysisDisplayNameVo.setAnalysisDisplayName(analysisType);
            resultList.add(isfdAnalysisDisplayNameVo);
        }
        return TableDataInfo.buildToPageMemoryLimit(Boolean.TRUE, resultList, pageNum, pageSize, (long) isfdAnalysisList.size());
    }

    @Override
    public List<IsfdAnalysisConfigVo> getAlgorithmArrangement(String analysisRefId) {
        LambdaQueryChainWrapper<IsfdAnalysisConfig> lambdaQuery = iIsfdAnalysisConfigService.lambdaQuery();
        lambdaQuery.eq(IsfdAnalysisConfig::getAnalysisRefId, analysisRefId);
        List<IsfdAnalysisConfig> isfdAnalysisConfigList = iIsfdAnalysisConfigService.list(lambdaQuery);
        List<IsfdAnalysisConfigVo> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(isfdAnalysisConfigList)) {
            resultList = MapstructUtils.convert(isfdAnalysisConfigList, IsfdAnalysisConfigVo.class);
            for (IsfdAnalysisConfigVo isfdAnalysisConfigVo : resultList) {
                if (IsfdAnalysisConfigNodeTypeEnum.OPERATOR.getValue().equals(isfdAnalysisConfigVo.getNodeType())
                    && StringUtils.isNotBlank(isfdAnalysisConfigVo.getOperatorRefId())) {
                    IsfdOperator isfdOperator = iIsfdOperatorService.getById(isfdAnalysisConfigVo.getOperatorRefId());
                    isfdAnalysisConfigVo.setDescription(isfdOperator.getOperatorName());
                }
            }
        }
        return resultList;
    }

    @Override
    public Boolean algorithmArrangementSave(AlgorithmArrangementBo algorithmArrangementBo) {
        // 1.先删除现有的在进行保存和更新操作
        String analysisRefId = algorithmArrangementBo.getAnalysisRefId();
        LambdaUpdateChainWrapper<IsfdAnalysisConfig> deleteLambdaUpdate = iIsfdAnalysisConfigService.lambdaUpdate();
        deleteLambdaUpdate.eq(IsfdAnalysisConfig::getAnalysisRefId, analysisRefId);
        iIsfdAnalysisConfigService.remove(deleteLambdaUpdate);

        // 2.解析node节点数据
        List<String> nodeOldIdList = new ArrayList<>();
        List<AlgorithmArrangementBo.Arrangement.Node> nodeList = algorithmArrangementBo.getArrangement().getNodeList();
        List<IsfdAnalysisConfig> isfdAnalysisConfigListForNode = new ArrayList<>();
        for (AlgorithmArrangementBo.Arrangement.Node node : nodeList) {
            nodeOldIdList.add(node.get_id());

            IsfdAnalysisConfig isfdAnalysisConfig = new IsfdAnalysisConfig();
            isfdAnalysisConfig.setAnalysisRefId(analysisRefId);
            isfdAnalysisConfig.setLabel(node.getLabel());
            isfdAnalysisConfig.setCoordinate(node.getCoordinate());
            isfdAnalysisConfig.setNodeType(node.getNodeType());
            isfdAnalysisConfig.setParent(node.getParent());
            isfdAnalysisConfig.setOperatorType(node.getOperatorType());
            isfdAnalysisConfig.setOperatorRefId(node.getOperatorRefId());
            isfdAnalysisConfigListForNode.add(isfdAnalysisConfig);
        }
        // 不能没有节点
        if (CollectionUtil.isEmpty(isfdAnalysisConfigListForNode)) {
            return Boolean.TRUE;
        }
        // 3.存储node节点数据
        iIsfdAnalysisConfigService.saveBatch(isfdAnalysisConfigListForNode);
        // 获取批量新增后的ids，因为框架没有返回ids的接口，所以查一遍
        LambdaQueryChainWrapper<IsfdAnalysisConfig> lambdaQuery = iIsfdAnalysisConfigService.lambdaQuery();
        lambdaQuery.eq(IsfdAnalysisConfig::getAnalysisRefId, analysisRefId);
        List<IsfdAnalysisConfig> list = iIsfdAnalysisConfigService.list(lambdaQuery);
        // 将新旧id拼接成map，用于更新linkList中的sourceRefId和targetRefId
        List<String> nodeNewIdList = list.stream().map(IsfdAnalysisConfig::get_id).toList();
        Map<String, String> oldToNewMap = IntStream.range(0, nodeOldIdList.size()).boxed().collect(Collectors.toMap(nodeOldIdList::get, nodeNewIdList::get));

        // 4.处理顺序流，顺序流也是一个node
        List<AlgorithmArrangementBo.Arrangement.Link> linkList = algorithmArrangementBo.getArrangement().getLinkList();
        List<IsfdAnalysisConfig> isfdAnalysisConfigListForLink = new ArrayList<>();
        for (AlgorithmArrangementBo.Arrangement.Link link : linkList) {
            IsfdAnalysisConfig isfdAnalysisConfig = new IsfdAnalysisConfig();
            isfdAnalysisConfig.setAnalysisRefId(analysisRefId);
            String sourceRefId = link.getSourceRefId();
            String targetRefId = link.getTargetRefId();
            isfdAnalysisConfig.setSourceRefId(oldToNewMap.get(sourceRefId));
            isfdAnalysisConfig.setTargetRefId(oldToNewMap.get(targetRefId));
            isfdAnalysisConfig.setEndAt(link.getEndAt());
            isfdAnalysisConfig.setStartAt(link.getStartAt());
            isfdAnalysisConfig.setNodeType(link.getNodeType());
            isfdAnalysisConfigListForLink.add(isfdAnalysisConfig);
        }

        // 有顺序流就保存
        if (CollectionUtil.isNotEmpty(isfdAnalysisConfigListForLink)) {
            iIsfdAnalysisConfigService.saveBatch(isfdAnalysisConfigListForLink);
        }

        // 5.跟新主集合数据，根据状态来更新发布状态和发布时间，选择原生mongodb的原因是因为实体类框架对字段进行null处理的时候不够精细化
        String status = algorithmArrangementBo.getStatus();
        Date now = new Date();
        if (AlgorithmArrangementEnum.publish.getValue().equals(status)) {
            MongoCollection<Document> mongoCollection = baseMapper.getMongoPlusClient().getCollection(DB_NAME, ANALYSIS_LIST_COLLECTION_NAME);
            Document filter = new Document(ID, new ObjectId(analysisRefId));
            Bson setUpdate = new Document($_SET, new Document()
                .append(IS_PUBLISHED, Boolean.TRUE)
                .append(PUBLISHED_TIME, now));
            mongoCollection.updateOne(filter, setUpdate);
        } else if (AlgorithmArrangementEnum.un_publish.getValue().equals(status)) {
            MongoCollection<Document> mongoCollection = baseMapper.getMongoPlusClient().getCollection(DB_NAME, ANALYSIS_LIST_COLLECTION_NAME);
            Document filter = new Document(ID, new ObjectId(analysisRefId));
            Bson setUpdate = new Document($_SET, new Document()
                .append(IS_PUBLISHED, Boolean.FALSE)
                .append(PUBLISHED_TIME, null));
            mongoCollection.updateOne(filter, setUpdate);
        }
        return Boolean.TRUE;
    }

    @Override
    public String selectByTableName() {
        return IsfdMetadataTableNameEnum.ANALYSIS_LIST.getValue();
    }

    @Override
    public Long excelImport(File excelImportFile, String metadataManagementId) {
        long successCount = 0L;

        try (InputStream is = new FileInputStream(excelImportFile)) {
            List<IsfdAnalysisVo> targetVos = ExcelUtil.importExcel(is, IsfdAnalysisVo.class);
            for (IsfdAnalysisVo vo : targetVos) {
                IsfdAnalysisBo bo = MapstructUtils.convert(vo, IsfdAnalysisBo.class);
                try {
                    // 转换json array 字符串为对象
                    String calculateObjectsJsonArrayStr = vo.getCalculateObjectsJsonArrayStr();
                    List<IsfdAnalysisBo.CalculateObject> calculateObjects = JsonUtils.parseArray(calculateObjectsJsonArrayStr, IsfdAnalysisBo.CalculateObject.class);
                    bo.setCalculateObjects(calculateObjects);
                    // 设置元数据管理id
                    bo.setMetadataManagementId(metadataManagementId);
                    this.add(bo);
                    successCount++;
                } catch (Exception e) {
                    log.error("算法库算法数据导入失败", e);
                }
            }

        } catch (Exception e) {
            log.error("sheet文件转换为实体类失败", e);
            throw new BaseException("sheet文件转换为实体类失败");
        }

        return successCount;
    }

}
